package cengxubianli

import "hufeng/ercahshu"

func averageOfLevels(root *ercahshu.TreeNode) []float64 {
	ans := make([]float64, 0)
	if root == nil {
		return ans
	}
	node := root
	stack := make([]*ercahshu.TreeNode, 0)
	stack = append(stack, node)
	for len(stack) > 0 {
		var cur float64
		n := len(stack)
		for i := 0; i < n; i++ {
			if stack[i].Left != nil {
				stack = append(stack, stack[i].Left)
			}
			if stack[i].Right != nil {
				stack = append(stack, stack[i].Right)
			}
			cur += float64(stack[i].Val)
		}
		ans = append(ans, cur/float64(n))
		stack = stack[n:]
	}
	return ans
}
